package com.basic.mq;

import com.basic.contant.RabbitContant;
import com.basic.util.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

@Component
public class MqMessageConsumer {

    final static Logger logger = LoggerFactory.getLogger(MqMessageConsumer.class);

    @Autowired
    private List<MqMessageHandler> mqMessageHandlers;

    @RabbitListener(queues = RabbitContant.QUEUE_NAME)
    public void listenMessage(String message) {
        logger.info("接收消息: {}", message);

        if(StringUtils.isEmpty(message)) {
            logger.info("接受消息, 消息为空");
            return;
        }
        MqMessageDTO messageDTO;
        try {
            messageDTO = JsonUtils.jsonToPojo(message, MqMessageDTO.class);
            if(messageDTO == null) {
                logger.info("接受消息, 消息转换为空, message:{}", message);
                return;
            }
        } catch (Exception e) {
            logger.info("接受消息, 消息转换异常, message:{}, e:{}", message, JsonUtils.objectToJson(e));
            return;
        }

        mqMessageHandlers.forEach(item -> {
            if(item.getMessageType().equals(messageDTO.getType())) {
                item.deal(messageDTO);
            }
        });

    }

}
